package com.zxlspace.thread;

public class SingletonTest {

    public static void main(String[] args) {
        Mythread2 t1 = new Mythread2(100);
        Mythread2 t2 = new Mythread2(500);
        Mythread2 t3 = new Mythread2(500);

        t1.start();
        t2.start();
        t3.start();

    /*    CarBean carBean1 = CarBean.getInstance();
        CarBean carBean2 = CarBean.getInstance();

        System.out.println(carBean1);
        System.out.println(carBean2);*/
    }

}


class Mythread2 extends Thread {

    private long time;

    public Mythread2(long time) {
        this.time = time;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+ "---->" + CarBean.getInstance(time));
    }
}

/**
 * 单例：饿汉式
 *
 */
class CarBean {
    private static CarBean instance = null;

    private CarBean() {

    }

    public static CarBean getInstance3(long time) {
        //如果多个线程进入当前代码块每个线程都要等待上一个线程执行完毕才能进入代码块，效率较低
        //添加double checking 提高多线程创建效率
        if (null == instance) {
            synchronized (CarBean.class) {
                if (instance == null) {
                    try {
                        Thread.sleep(time);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    instance = new CarBean();
                }

            }
        }
        return instance;
    }

    public static CarBean getInstance2(long time) {
        //如果多个线程进入当前代码块每个线程都要等待上一个线程执行完毕才能进入代码块，效率较低
        synchronized (CarBean.class) {
            if (instance == null) {
                try {
                    Thread.sleep(time);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                instance = new CarBean();
            }

        }
        return instance;
    }

    //synchronized 同步方法，synchronized 加在静态方法上是锁住整个类对象,加锁解锁性能开销较大
    public static synchronized CarBean getInstance1(long time) {
        if (instance == null) {
            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            instance = new CarBean();
        }
        return instance;
    }

    public static CarBean getInstance(long time) {
        if (instance == null) {
            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            instance = new CarBean();
        }

        return instance;
    }
}

/**
 * 单例：饿汉式
 * 实例对象在加载时不创建，在使用时创建
 */
class CarBean2 {
    private static class CarBeanHoldle {
        private static CarBean2 instance = new CarBean2();
    }

    private CarBean2() {

    }

    public static CarBean2 getInstance() {
        return CarBeanHoldle.instance;
    }
}